const promisify = require('util').promisify
const path = require('path')
const fs = require('fs')
const execFile = promisify(require('child_process').execFile)
const readdirPromise = promisify(fs.readdir)
const readFilePromise = promisify(fs.readFile)
const unlinkPromise = promisify(fs.unlink)
const writeFilePromise = promisify(fs.writeFile)
const statPromise = promisify(fs.stat)
const mvExe = 'C:\\Program Files\\Git\\usr\\bin\\mv.exe'

const targetPath = process.cwd()

const readdir = async (targetPath) => {
  const files = await readdirPromise(targetPath)
  return files
}

const readFile = async (filePath) => {
  const file = await readFilePromise(filePath)
  return file
}

const reflesh = async (targetPath) => {
  const files = await readdir(targetPath)
  for (let i = 0; i < files.length; i++) {
    const filename = files[i]
    if (filename === 'node_modules') continue
    const filePath = path.join(targetPath, filename)
    const stat = await statPromise(filePath)
    if (stat.isDirectory()) {
      reflesh(filePath)
    } else {
      const tempPath = filePath + '.tmp'
      const file = await readFile(filePath)
      await unlinkPromise(filePath)
      await writeFilePromise(tempPath, file)
      await execFile(mvExe, [tempPath, filePath])
    }
  }
}

reflesh(targetPath)
